﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using System.Collections.Generic;
using PowerStation.RequestModel;
using Microsoft.EntityFrameworkCore;
using Masuit.Tools;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 权限管理
    /// </summary>
    public class PermissionController : BaseApi<PermissionController>
    {
        /// <summary>
        /// 权限管理
        /// </summary>
        /// <param name="content"></param>
        public PermissionController(IHttpContextAccessor content) : base(content)
        {
        }


        /// <summary>
        /// 新增权限组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<decimal>> RoleCreate(tRole model)
        {
            model.roleId = 0;
            model.dataState = 0;
            await this._db.tRole.AddAsync(model);
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<decimal>(model.roleId > 0, model.roleId);
        }


        /// <summary>
        /// 配置权限组权限
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> RolePermissionModify(RequestRolePerssionModel model)
        {

            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tRolePermission.Where(x => x.role_roleId_fk == model.roleId).DeleteAsync();
                await this._db.SaveChangesAsync();
                await this._db.tRolePermission.AddRangeAsync(model.keyId.Select(x => new tRolePermission {
                    permission_keyId_fk = x,
                    role_roleId_fk = model.roleId
                }).ToList());
                await this._db.SaveChangesAsync();
                tran.Commit();
            }
            return ResultApi.okOrError<bool>(true, true);
        }

        /// <summary>
        /// 返回角色组权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<tRolePermission>>> RolePermissionList(decimal roleId)
        {
            IQueryable<tRolePermission> q = this._db.tRolePermission.Where(x=>x.role_roleId_fk == roleId);
            return ResultApi.ok<List<tRolePermission>>(await q.ToListAsync(), 0);
        }



        /// <summary>
        /// 权限组修改
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> RoleModify(tRole model)
        {
            int count = await this._db.tRole.Where(x => x.roleId == model.roleId).UpdateAsync(x => new tRole {
                dataState = model.dataState,
                roleName = model.roleName,
                roleNote = model.roleNote,

            });
            if (count > 0) await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count > 0, count > 0);
        }



        /// <summary>
        /// 权限组删除
        /// </summary>
        /// <param name="roleIds">权限id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> RoleDelete(List<decimal> roleIds)
        {
            int count = await this._db.tRole.Where(x => roleIds.Contains(x.roleId)).UpdateAsync(x => new tRole { dataState = 1 });
            if (count == roleIds.Count) await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count == roleIds.Count, count == roleIds.Count);
        }



        /// <summary>
        /// 冻结权限组
        /// </summary>
        /// <param name="enable">是否冻结</param>
        /// <param name="roleIds">权限组ID</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultApi<bool>> RoleEnable(List<decimal> roleIds, bool enable)
        {
            int count = await this._db.tRole.Where(x => x.dataState != 1 && roleIds.Contains(x.roleId)).UpdateAsync(x => new tRole { dataState = enable ? 2 : 0 });
            if (count == roleIds.Count) await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(count == roleIds.Count, count == roleIds.Count);
        }



        /// <summary>
        /// 权限组添加账号,每次都要把选中的全部传上来.无论是新选的还是已存在的,如果要清空人员,只传一条,附上上权限组roleId,userPermission_userId_fk为0
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<bool>> RoleAddUser(List<tUserRole> lst)
        {
            if (lst.Count == 0) return ResultApi.error(false, "人员不能为空");
            var disCount = lst.Select(x => x.userRole_roleId_fk).Distinct();
            if (disCount.Count() > 1) return ResultApi.error(false,"一次只能操作一个角色权限");
            if (disCount.First() <= 0) return ResultApi.error(false,"角色组ID不能 >= 0");
            var userIds = lst.Select(x=>x.userPermission_userId_fk).Distinct();
            
            if (userIds.Count() == 1 && userIds.First() == 0)
            {
                //清除所有
                await this._db.tUserRole.Where(x => x.userRole_roleId_fk == lst[0].userRole_roleId_fk).DeleteAsync();
                await this._db.SaveChangesAsync();
                return ResultApi.okOrError<bool>(true, true);
            }
            else {
                var addLst = userIds.Select(x => new tUserRole()
                {
                    userRole_roleId_fk = disCount.First(),
                    userPermission_userId_fk = x
                }).ToList();
                using (var tran = await this._db.Database.BeginTransactionAsync())
                {
                    await this._db.tUserRole.Where(x => x.userRole_roleId_fk == lst[0].userRole_roleId_fk).DeleteAsync();
                    await this._db.SaveChangesAsync();

                    await this._db.tUserRole.AddRangeAsync(addLst);
                    await this._db.SaveChangesAsync();

                    var ok = addLst.Where(x => x.userPermissionId > 0).Count() == userIds.Count();
                    if (ok) tran.Commit();
                    return ResultApi.okOrError<bool>(ok, ok);
                }
                
            }
           
        }


        /// <summary>
        /// 返回权限角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vRole>>> RoleList([FromQuery] RequestMultipleSearchModel model)
        {
            IQueryable<vRole> q = this._db.vRole;
            foreach (var item in model.searchItem)
            {
                if (item.typeName == "角色名称")
                {
                    q = q.Where(x => x.roleName.Contains(item.value));
                }
                else if (item.typeName == "角色状态") { 
                    q = q.Where(x => x.dataState == item.value.ConvertTo<int>());
                }
            }
            var result = await model.setPageAsync(q);
            return ResultApi.ok<List<vRole>>(await result.Item2.ToListAsync(), result.Item1); ;
        }


        /// <summary>
        /// 返回角色成员列表
        /// </summary>
        /// <param name="roleId">角色ID,不传返回所有</param>
        /// <param name="model">分页</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vUserRole>>> RoleUserList(decimal? roleId,[FromQuery]PageModel model)
        {
            IQueryable<vUserRole> q = this._db.vUserRole;
            if (roleId.HasValue)
            {
                q = q.Where(x => x.userRole_roleId_fk == roleId);
            }
            var result = await model.setPageAsync(q);
            return ResultApi.ok<List<vUserRole>>(await result.Item2.ToListAsync(), result.Item1);
        }

        /// <summary>
        /// 删除角色成员
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> RoleUserDelete(decimal roleId,decimal userId)
        {
            await this._db.tUserRole.Where(x => x.userRole_roleId_fk == roleId && x.userPermission_userId_fk == userId).DeleteAsync();
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(true, true);
        }

    }
}
